package com.lkqm.seckill.controller;

import com.lkqm.seckill.dictionary.SeckillStateEnum;
import com.lkqm.seckill.dto.Exposer;
import com.lkqm.seckill.dto.SeckillExecution;
import com.lkqm.seckill.dto.SeckillResult;
import com.lkqm.seckill.entity.Seckill;
import com.lkqm.seckill.exception.RepeatSeckillException;
import com.lkqm.seckill.exception.SeckillClosedException;
import com.lkqm.seckill.exception.SeckillException;
import com.lkqm.seckill.service.SeckillService;
import com.sun.corba.se.spi.orbutil.fsm.Guard;
import com.sun.javafx.sg.prism.NGShape;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import java.util.List;

/**
 * 秒杀控制层
 * Created by luokaiqiongmou on 2016/11/28.
 */
@Controller
@RequestMapping(value = "/seckill")
public class SeckillController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Inject
    SeckillService seckillService;

    /**
     * 秒杀列表
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        List<Seckill> seckillList = seckillService.getSeckillList();
        model.addAttribute("seckillList", seckillList);
        return "list";
    }

    /**
     * 秒杀商品详情
     *
     * @param seckillId
     * @param model
     * @return
     */
    @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET)
    public String detail(@PathVariable("seckillId") Long seckillId, Model model) {
        if (seckillId == null) {
            return "redirect:/seckill/list";
        }
        Seckill seckill = seckillService.getById(seckillId);
        if (seckill == null) {
            return "forward:/seckill/list";
        }
        model.addAttribute("seckill", seckill);
        return "detail";
    }

    /**
     * 暴露秒杀接口
     *
     * @param seckillId
     * @return
     */
    @RequestMapping(value = "/{seckillId}/exposer",
            method = RequestMethod.GET,
            produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public SeckillResult<Exposer> exposeUrl(@PathVariable("seckillId") Long seckillId) {
        SeckillResult<Exposer> result;
        try {
            Exposer exposer = seckillService.exportSeckillUrl(seckillId);
            result = new SeckillResult<Exposer>(true, exposer);
        } catch (Exception e) {
            logger.error(e.getMessage());
            result = new SeckillResult<Exposer>(false, e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/{seckillId}/{md5}/kill",
            method = RequestMethod.POST,
            produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public SeckillResult<SeckillExecution> seckill(@PathVariable("seckillId") Long id,
                                                   @CookieValue(value = "killPhone", required = false) Long phone,
                                                   @PathVariable("md5") String md5) {
            SeckillResult<SeckillExecution> result;
        if(phone == null) {
            return new SeckillResult<SeckillExecution>(false, "未注册");
        }
        try {
            // 执行秒杀
            SeckillExecution execution = seckillService.executeSeckillProcedure(id, phone, md5);
            return new SeckillResult<SeckillExecution>(true, execution);
        } catch (RepeatSeckillException e) {
            // 重复秒杀
            SeckillExecution execution = new SeckillExecution(SeckillStateEnum.REPEAT_SECKILL);
            return new SeckillResult<SeckillExecution>(false, execution);
        } catch (SeckillClosedException e) {
            // 秒杀为开启，或已经关闭
            SeckillExecution execution = new SeckillExecution(SeckillStateEnum.CLOSED_SECKILL);
            return new SeckillResult<SeckillExecution>(false, execution);
        } catch (SeckillException e) {
            // 内部错误
            SeckillExecution execution = new SeckillExecution(SeckillStateEnum.DATA_REWRITE);
            return new SeckillResult<SeckillExecution>(false, execution);
        }
    }

    @RequestMapping(value="/time/now", method = RequestMethod.GET)
    @ResponseBody
    public SeckillResult<Long> now() {
        return new SeckillResult<Long>(true, System.currentTimeMillis());
    }

}
